﻿var YdbOpen = {
    callbacksCount: 1,
    callbacks: {},

    resultForCallback: function resultForCallback(callbackId, result) {
        try {
            var callback = YdbOpen.callbacks[callbackId];
            if (!callback) return;

            callback.apply(null, result);
        } catch (e) { alert(e); }
    },

    call: function call(functionName, args, callback) {
        var hasCallback = callback && typeof callback == "function";
        var callbackId = hasCallback ? YdbOpen.callbacksCount++ : 0;

        var ua = navigator.userAgent.toLowerCase(),
            isIos = ua.match(/(iphone|ipod|ipad);?/i),
            isAndroid = ua.match(/android/i);

        if (hasCallback)
            YdbOpen.callbacks[callbackId] = callback;

        if (isIos) {
            var iframe = document.createElement("iframe");
            iframe.setAttribute("src", "YdbOpenJs||" + functionName + "||" + callbackId + "||" + JSON.stringify(args));
            document.documentElement.appendChild(iframe);
            iframe.parentNode.removeChild(iframe);
            iframe = null;
            try {
                window.webkit.messageHandlers.YdbOpen.postMessage(functionName + "||" + callbackId + "||" + JSON.stringify(args));
            } catch (e) { ; }
        } else if (isAndroid) {
            window.YdbOpenJs.Call(functionName,callbackId, JSON.stringify(args));
        }
    }
};
